import React, {useState} from 'react';
import axios from 'axios';

interface LoginProps {
    setIsLoggedIn: React.Dispatch<React.SetStateAction<boolean>>;
    setRole: React.Dispatch<React.SetStateAction<string>>;
}

interface UserCredentials {
    token(arg0: string, token: any): unknown;
    loginName: string;
    password: string;
}

const Login: React.FC<LoginProps> = ({ setIsLoggedIn, setRole }) => {
    const [loginName, setLoginName] = useState('');
    const [password, setPassword] = useState('');
    const [isUser, setIsUser] = useState(true);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        try {
            const response = await axios.post<UserCredentials>(
                `/api/${isUser ? 'users' : 'admins'}/login`,
                { loginName, password }
            );
            // @ts-ignore
            localStorage.setItem('token', response.data.token);
            localStorage.setItem('role', isUser ? 'user' : 'admin');
            setIsLoggedIn(true);
            setRole(isUser ? 'user' : 'admin');
        } catch (error) {
            console.error('Login failed:', error);
            alert('Invalid login credentials');
        }
    };

    return (
        <div>
            <h2>{isUser ? 'User Login' : 'Admin Login'}</h2>
            <form onSubmit={handleSubmit}>
                <div>
                    <label htmlFor="loginName">Login Name:</label>
                    <input
                        type="text"
                        id="loginName"
                        value={loginName}
                        onChange={(e) => setLoginName(e.target.value)}
                        required
                    />
                </div>
                <div>
                    <label htmlFor="password">Password:</label>
                    <input
                        type="password"
                        id="password"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        required
                    />
                </div>
                <button type="submit">Login</button>
            </form>
            <button onClick={() => setIsUser(!isUser)}>
                Switch to {isUser ? 'Admin' : 'User'} Login
            </button>
        </div>
    );
};

export default Login;